<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 专项治理评分编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}" id="base-breadcrumb" style="position: relative">
      <a-spin :spinning="loading[0] || loading[1] || loading[2]">
        <!-- 基本信息 -->
        <a-card>
          <title-name title="基本信息"></title-name>
          <custom-form 
            :formList="formList" 
            :form="form" 
            :editModel="editModel == 0 || columns.length > 0 ? 'V' : ''"
            @getList="getCusFormList"
            @select="getCusFormSelect"
            @selectOrg="getCusFormOrg"
          >
            <template #gradeYear>
              <a-date-picker
                v-model="form.gradeYear"
                mode="year"
                :allowClear="false"
                v-if="columns.length == 0"
                format="YYYY"
                placeholder="请选择年度"
                :open="yearPickShow"
                @panelChange="handlePanelChange"
                @openChange="handleOpenChange"
              />
              <span v-else>{{ form.gradeYear }}</span>
            </template>
            <template #gradeEmployeeId>
              <div class="flex">
                <a-input placeholder="请选择" v-model="form.gradeEmployeeName" size="default" style="margin-right: 20px;" disabled v-if="columns.length == 0" />
                <span v-else>{{ form.gradeEmployeeName }}</span>
                <a-button type="primary" v-if="columns.length == 0" @click="gradeEmployeeIdVisible = true">选择</a-button>
                <!-- 单选人员 -->
                <SelectPersonModal
                  v-if="columns.length == 0"
                  :visible.sync="gradeEmployeeIdVisible"
                  @confirmSelect="(e) => handleGradeEmployeeId(e)"
                />
              </div>
            </template>
          </custom-form>
        </a-card>
        <!-- 评分 -->
        <a-card v-if="editModel != 2 || nextStep" style="margin-bottom: 50px">
          <title-name :title="`${form.cateName || ''}评分`"></title-name>
          <s-table ref="table" size="default" rowKey="id" :columns="columns" bordered :data="loadData" :showPagination="false">
            <!-- 考核情况 -->
            <div v-if="columns.length > 0" :slot="columns.length > 0 ? columns.find((item) => item.code === '-1').dataIndex : ''" slot-scope="text, record">
              <div v-if="editModel != 0">
                <a-row type="flex" :gutter="10" v-if="record.defaultScore || record.evalue" style="flex-wrap: nowrap">
                  <BaseInput
                    v-if="(record.defaultScore || record.evalue) && editModel != 0"
                    style="width: 100%"
                    :maxLength="300"
                    placeholder="请输入考核情况"
                    v-model="record[columns.find((item) => item.code === '-1').dataIndex]"
                  ></BaseInput>
                  <a class="ml12" @click="handleCancel(record)" style="flex-shrink: 0">取消打分</a>
                </a-row>
              </div>
              <ellipsis v-if="editModel == 0" tooltip :length="45">{{ text }}</ellipsis>
              <template v-if="!record.defaultScore && !record.evalue">
                <a class="del_btn" v-if="editModel == 0">未打分</a>
                <a v-else @click="record.evalue = true">打分</a>
              </template>
            </div>
            <!-- 打分 -->
            <div v-if="columns.length > 0" :slot="columns.length > 0 ? columns.find((item) => item.code === '-2').dataIndex : ''" slot-scope="text, record">
              <BaseInputNumber
                v-if="(record.defaultScore || record.evalue) && editModel != 0"
                style="width: 100%"
                :max="Number(record[columns.find((item) => item.code === '4').dataIndex] || 0)"
                :precision="2"
                :min="0"
                placeholder="请输入得分"
                v-model="record[columns.find((item) => item.code === '-2').dataIndex]"
              ></BaseInputNumber>
              <div v-if="editModel == 0">{{ record[columns.find((item) => item.code == '-2').dataIndex] }}</div>
            </div>
            <!-- 备注 -->
            <div v-if="columns.length > 0" :slot="columns.length > 0 ? columns.find((item) => item.code === '-3').dataIndex : ''" slot-scope="text, record">
              <BaseTextarea
                  v-if="(record.defaultScore || record.evalue) && editModel != 0"
                  v-model="record[columns.find((item) => item.code === '-3').dataIndex]"
                  placeholder="请输入备注"
                  style="width: 100%"
                  :maxLength="10000"
                  :showLimitTip="false"
                  :auto-size="{ minRows: 1, maxRows: 5 }"
                />
              <ellipsis v-if="editModel == 0" tooltip :length="45">{{ text }}</ellipsis>
            </div>
            <!-- 统计 -->
            <div align="right" slot="footer">
              <span class="mr20">总分：{{ totalScore }}分</span>
              <span class="mr20">评价得分：{{ score }}分</span>
              <span>换算百分制得分：{{ totalScore ? ((score * 100) / totalScore).toFixed(2) : 0 }}分</span>
            </div>
          </s-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button :loading="loading[2]" v-if="editModel == 2 && !nextStep" type="primary" class="button_right" @click="handleNext">下一步</a-button>
        <template v-else>
          <!-- <a-button :disabled="loading[0] || loading[1]" v-if="editModel == 1 && statusCode === '0' && form.version && form.version <= 1" type="danger" class="button_right" @click="handleRemove">删除草稿</a-button> -->
          <a-button :loading="loading[0]" :disabled="loading[1]" v-if="editModel != 0 && columns.length > 0" type="primary" class="button_right" @click="handleSubmit(0)">保存草稿</a-button>

          <a-button :loading="loading[1]" :disabled="loading[0]" v-if="editModel != 0 && columns.length > 0" type="primary" class="button_right" @click="handleSubmit(1)"
            >提交</a-button
          >
        </template>
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components' // 表格
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector' // 状态
import { riskGradeTable, riskGrade } from '@/api/quality/riskGrade' // api
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    Ellipsis,
    SelectPersonModal: () => import('@/components/SelectPersonModal')
  },
  data() {
    return {
      yearOpen: false, // 年份显隐控件
      gradeEmployeeIdVisible: false, // 选择评价人
      loading: { 0: false, 1: false, 2: false }, // 草稿和提交按钮loding:0 保存;1 提交;2 下一步
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      nextStep: false, // 是否为下一步
      id: '', // 业务id
      form: {
        fillerDate: '',
        fillerEmployeeId: '',
        viewName: ""
      }, // 表单
      statusCode: '', // 审批状态
      rules: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择评价类型', trigger: 'change' }],
        tableId: [{ required: true, message: '请选择评价表名称', trigger: 'change' }],
        gradeYear: [{ required: true, message: '请选择年度', trigger: 'change' }],
        gradeEmployeeId: [{ required: true, message: '请选择评价人', trigger: 'change' }],
      },
      loadData: () => {
        if (this.editModel != 2 || this.nextStep) {
          let args = {}
          if (this.id) {
            args.id = this.id
          }
          this.loading[0] = true
          return riskGrade
            .getDetail(args)
            .then((res) => {
              if (res.data) {
                let datas = this.$clone(res)
                // 映射项目信息
                this.form = datas.data || {}
                this.form.viewName = this.form.branchComName + "/" + this.form.projectName
                this.id = res.data.id
                this.statusCode = res.data.statusCode
                // 映射表头
                this.columns = res.data.header.map((item) => {
                  // 若表头是考核内容
                  if (item.code == '1') {
                    this.$nextTick(() => {
                      // 自定义单元格，将考核内容列一样的行合并
                      item.customRender = (value, row, index) => {
                        const obj = {
                          children: value,
                          attrs: {}
                        }
                        // 若该行考核内容和上一行一致，则使其隐藏
                        if (index != 0 && res.data.content[index - 1][item.dataIndex] == value) {
                          obj.attrs.rowSpan = 0
                          // 若不是，则往下合并与改行考核内容一致行的总行数
                        } else {
                          obj.attrs.rowSpan = this.$clone(res.data.content).filter((i) => i[item.dataIndex] == value).length
                        }
                        return obj
                      }
                    })
                  }
                  // 若表头是考核情况、打分时，自定义列
                  if (item.code === '-1' || item.code === '-2' || item.code === '-3') {
                    item.scopedSlots = { customRender: item.dataIndex }
                    item.width = 260
                  }
                  item.ellipsis = true
                  return item
                })
                // 映射表格列表
                datas.data = res.data.content.map((item) => {
                  // 添加打分标志
                  item.defaultScore = item[this.$clone(res.data.header).find((item) => item.code == '-2').dataIndex]
                  item.evalue = item.defaultScore ? true : false
                  return item
                })
                // 列表对象
                this.content = datas.data
                return datas
              }
            })
            .finally((res) => {
              this.loading[0] = false
            })
        }
      },
      // 表头
      columns: [],
      content: [],
      cate: '',
      typeIdList: [],
      yearPickShow: false,
    }
  },
  created() {
    const title0 = ['过程评价查看', '过程评价编辑', '过程评价新增']
    const title1 = ['竣工评价查看', '竣工评价编辑', '竣工评价新增']
    if (this.cate == '0') {
      this.$route.meta.title = title0[this.editModel]
    } else if (this.cate == '1') {
      this.$route.meta.title = title1[this.editModel]
    }
    // 为添加操作时
    if (this.editModel == 2) {
      this.form.fillerEmployeeName = this.$userInfo()?.name
      this.form.fillerEmployeeId = this.$userInfo()?.employee?.id
      this.form.fillerDate = this.$dateFormat(new Date(), 'D')
    }
  },
  computed: {
    // 总分
    totalScore() {
      let total = 0
      let dataIndex = this.columns.find((item) => item.code === '4')?.dataIndex //得分字段
      let content = this.content.filter((item) => item.evalue) // 评分列表
      if (content.length === 1) {
        total = content[0][dataIndex] || 0
      } else if (content.length > 1) {
        total = content.reduce((t, i) => {
          return Number(t[dataIndex] || t || 0) + Number(i[dataIndex] || 0)
        })
      }
      return total
    },
    // 得分
    score() {
      let total = 0
      let dataIndex = this.columns.find((item) => item.code === '-2')?.dataIndex //打分字段
      let dataIndex2 = this.columns.find((item) => item.code === '4')?.dataIndex //得分字段
      let content = this.content.filter((item) => item.evalue) // 评分列表
      if (content.length === 1) {
        // 打分超过限制则为0
        total = Number(content[0][dataIndex] >= 0) && Number(content[0][dataIndex]) <= Number(content[0][dataIndex2]) ? Number(content[0][dataIndex]) : 0
      } else if (content.length > 1) {
        total = content.reduce((t, i) => {
          return (
            Number(t[dataIndex] || t || 0) + Number(Number(i[dataIndex]) >= 0 && Number(i[dataIndex]) <= Number(i[dataIndex2]) ? Number(i[dataIndex]) : 0) // 打分超过限制则为0
          )
        })
      }
      if (isNaN(total)) {
        return 0
      }
      return total <= 0 ? 0 : Number(total).toFixed(2)
    },
    // 表单列表
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          isAutoSelectFirst: this.editModel == 2,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: this.columns.length > 0,
          isNoBorder: this.columns.length > 0,
          viewName: "viewName",
        },
        {
          keyName: 'typeId',
          viewName: 'typeName',
          type: Selector,
          label: '评价类型',
          attrs: {
            selectType: '64',
            // labelInValue: false,
            mode: 'default',
            filterFn: (item) => this.cate === '0' ? item.code !== '2': item.code === '2'
          }
        },
        {
          type: 'a-select',
          keyName: 'tableId',
          viewName: 'tableName',
          label: '评价表名称',
          data: this.typeIdList
        },
        {
          hidden: this.cate !== '0',
          keyName: 'gradeYear',
          type: 'a-date-picker',
          label: '年度',
          slot: true,
        },
        {
          keyName: 'gradeEmployeeId',
          type: 'a-input',
          label: '评价人',
          slot: true
        },
        {
          keyName: 'fillerEmployeeName',
          type: 'a-input',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    }
  },
  methods: {
    handleOpenChange(status) {
      this.yearPickShow = status;
    },
    handlePanelChange(value) {
      this.$set(this.form, 'gradeYear', value)
      this.yearPickShow = false;
      this.$nextTick(() => {
        // 触发表单校验
        this.$refs.ruleForm?.validateField('gradeYear')
      })
    },
    getRiskGradeTable() {
      riskGradeTable.postList({needCount: false, typeId: this.form.typeId}).then((res) => {
          if (res.data) {
            this.typeIdList = res.data.filter(item => +item.enabled == 1).map(item => {
              item.label = item.name
              item.value = item.id
              return item
            })
            return res
          } else {
            this.typeIdList = []
          }
        })
    },
    getCusFormOrg(val) {
      if(val&&val.length) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.viewName = val[val.length - 2].orgName + "/" + val[val.length - 1].projectName
      }
    },
    /**
     * 取消评分
     */
    handleCancel(e) {
      let memo = e[this.columns.find((item) => item.code === '-1').dataIndex] // 考核情况
      let value = e[this.columns.find((item) => item.code === '-2').dataIndex] // 打分
      // 取消打分
      e.evalue = false
      // 重置考核情况
      memo && (e[this.columns.find((item) => item.code === '-1').dataIndex] = '')
      // 重置初始打分值和真实打分值
      e.defaultScore = ''
      e[this.columns.find((item) => item.code === '-2').dataIndex] = ''
    },
    // Selector 选择
    getCusFormSelect(name, e) {
      if (name === 'typeId') {
        this.$set(this.form, 'tableId', '')
        this.getRiskGradeTable()
      }
    },
    handleGradeEmployeeId(e) {
      this.gradeEmployeeIdVisible = false
      this.$set(this.form, 'gradeEmployeeName', e.name)
      this.$set(this.form, 'gradeEmployeeId', e.id)
      this.$nextTick(() => {
        // 触发表单校验
        this.$refs.ruleForm?.validateField('gradeEmployeeId')
      })
    },
    getCusFormList(name, e) {
    },
    /**
     * 下一步
     */
    handleNext() {
      let that = this
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          that.$confirm({
            title: '温馨提示',
            content: '生成评分表后基本信息不能再修改，确认进行下一步？',
            onOk: () => {
              // 校验表单
              return new Promise((resolve, reject) => {
                that.$refs.ruleForm.validate((e) => {
                  if (e) {
                    // 提交表单
                    let form = that.$clone(that.form)
                    form.status = 0
                    form.cate = this.cate
                    let submitText = this.cate == '0' ? '过程评价成功！' : '竣工评价成功！'
                    riskGrade
                      .create(form)
                      .then((res) => {
                        resolve()
                        that.$message.success(submitText)
                        that.id = res.data.id
                        that.nextStep = true // 进行下一步
                      })
                      .catch((res) => {
                        // that.$message.warning(res?.data?.message || '生成评分表失败！')
                        reject()
                      })
                  }
                })
              })
            }
          })
        }
      })
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return riskGrade.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          let content = that.$clone(that.content)
          let dataIndex = that.columns.find((item) => item.code == '-2').dataIndex // 打分的key
          // 判断是否有激活评分项
          if (that.$clone(content).filter((item) => item.evalue)?.length > 0 || statusCode == 0) {
            // 提交表单
            this.$confirm({
              title: '温馨提示',
              content: `确定${['保存', '提交'][statusCode]}!`,
              onOk: () => {
                that.loading[statusCode] = true
                let form = that.$clone(that.form)
                content.forEach((item) => {
                  item.evalue && (item[dataIndex] = item[dataIndex] || '0')
                })
                form.content = content
                form.status = statusCode ? 'SUBMITTED' : 'DRAFT'
                form.score = this.score
                form.totalScore = this.totalScore
                let name = ['create', 'update'][that.id ? 1 : 0] // 根据操作切换url地址
                riskGrade[name](form)
                  .then((res) => {
                    that.loading[statusCode] = false
                    that.$message.success(['保存', '提交'][statusCode] + '成功！')
                    that.$multiTab.close()
                  })
                  .catch((res) => {
                    // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
                    that.loading[statusCode] = false
                  })
              }
            })
            
          } else {
            this.$message.warning('请评分后操作！')
          }
        }
      })
    }
  }
}
</script>
